import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import Welcome from '@/views/Welcome.vue'
import Goods from '@/views/goods/Goods.vue'
import Order from '@/views/order/Order.vue'
import User from '@/views/User.vue'
import Role from '@/views/power/Role.vue'
import Limit from '@/views/power/Limit.vue'
import Stat from '@/views/Stat.vue'
import GoodsDetail from '@/views/goods/GoodsDetail.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home/welcome'
  },
  {
    path: '/home',
    redirect: '/home/welcome',
    component: Home,
    children: [
      { path: 'welcome', component: Welcome },
      { path: 'goods', component: Goods },
      { path: 'order', component: Order },
      { path: 'user', component: User },
      { path: 'role', component: Role },
      { path: 'limit', component: Limit },
      { path: 'Stat', component: Stat },
      { path: 'goodsDetail', component: GoodsDetail },
      // 因编辑商品根据id，所以使用动态路由
      { path: 'goodsDetail/:id', component: GoodsDetail }
    ]
  },
  {
    path: '/login',
    component: Login
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    // 判断是否有token
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
